package cn.edu.sdu.order.backend.service.impl;

import cn.edu.sdu.order.backend.constant.PrefixConstant;
import cn.edu.sdu.order.backend.dao.OrderMapper;
import cn.edu.sdu.order.backend.dto.GoodsDTO;
import cn.edu.sdu.order.backend.model.Order;
import cn.edu.sdu.order.backend.model.OrderExample;
import cn.edu.sdu.order.backend.model.Token;
import cn.edu.sdu.order.backend.service.GoodsService;
import cn.edu.sdu.order.backend.service.KeyMaxValueService;
import cn.edu.sdu.order.backend.service.utils.GoodsUtils;
import cn.edu.sdu.order.backend.utils.TokenContextHolder;
import cn.edu.sdu.order.backend.vo.GoodsVO;
import com.alibaba.fastjson.JSON;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsServiceImpl implements GoodsService {


    @Autowired
    private KeyMaxValueService keyMaxValueService;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public String create(GoodsDTO goodsDTO) {
        Token token = TokenContextHolder.getToken();
        Order order = new Order();
        String beginning0 = goodsDTO.getBeginning().get(0).toString();
        String beginning1 = goodsDTO.getBeginning().get(1).toString();
        String beginning = beginning0+","+beginning1;
        order.setBeginning(beginning);
        // 不需要设置目标的经纬度
        order.setDestination("100.0,100.0");
        order.setGoodsCode(keyMaxValueService.generateBusinessCode(PrefixConstant.GOODS));
        // 初始化一个温度 10度
        double temp = 10.0;
        order.setTemperature((float) temp);
        // 初始化一个适度 10%
        double hum = 10.0;
        order.setHumidity((float) hum);
        order.setOwner(token.getUserCode());
        order.setDeleted(0);
        order.setTrack(order.getBeginning());
        // TODO 等写完FPGA模块需要来修改，这里先写死
        order.setFpgaCode("FG00002");
        order.setState(0);
        orderMapper.insert(order);
        return order.getGoodsCode();
    }

    @Override
    public List<GoodsVO> list(String userId) {
        OrderExample orderExample = new OrderExample();
        orderExample.createCriteria()
                .andOwnerEqualTo(userId)
                .andDeletedEqualTo(0);
        List<Order> orders = orderMapper.selectByExample(orderExample);
        return orders.stream()
                .map(GoodsUtils::convertToVo)
                .collect(Collectors.toList());
    }

    @Override
    public GoodsVO get(String orderCode) {
        OrderExample orderExample = new OrderExample();
        orderExample.createCriteria()
                .andGoodsCodeEqualTo(orderCode);
        List<Order> orders = orderMapper.selectByExample(orderExample);
        Order order = orders.get(0);
        return GoodsUtils.convertToVo(order);
    }

    @Override
    public String delete(String goodsCode, Integer userType) {
        Token token = TokenContextHolder.getToken();
        OrderExample orderExample = new OrderExample();
        orderExample.createCriteria()
                .andOwnerEqualTo(token.getUserCode())
                .andGoodsCodeEqualTo(goodsCode);
        List<Order> orders = orderMapper.selectByExample(orderExample);
        if(orders.isEmpty()) {
            throw new RuntimeException("未找到订单或者订单不属于您");
        } else {
            Order order = orders.get(0);
            order.setDeleted(1);
            OrderExample orderExample1 = new OrderExample();
            orderExample1.createCriteria()
                    .andGoodsCodeEqualTo(goodsCode);
            int updated = orderMapper.updateByExampleSelective(order, orderExample1);
            if(updated!=1) {
                throw new RuntimeException("删除失败");
            } else {
                return order.getGoodsCode();
            }
        }
    }

    @Override
    public GoodsVO update(String goodsCode) {
        OrderExample orderExample = new OrderExample();
        orderExample.createCriteria()
                .andGoodsCodeEqualTo(goodsCode);
        List<Order> orders = orderMapper.selectByExample(orderExample);
        Order order = orders.get(0);
        // TODO 这里请求FPGA端
        String url = "http://121.196.102.121:5000/get";
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        try(Response response = okHttpClient.newCall(request).execute()) {
            String data = response.body().string();
            JSON json = JSON.parseObject(data);
//            order.setHumidity(json);
        } catch (IOException e) {
//            e.printStackTrace();
            throw new RuntimeException("FPGA端出错");
        }
        return GoodsUtils.convertToVo(order);
    }
}
